package xyz.jcat.seata.example.points.dubbo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.jcat.common.exception.BusinessException;
import xyz.jcat.seata.example.api.IPointsService;
import xyz.jcat.seata.example.api.dto.PointsIncrDto;
import xyz.jcat.seata.example.api.exception.ProviderException;
import xyz.jcat.seata.example.points.domain.dao.IUserPointsDao;
import xyz.jcat.seata.example.points.domain.po.UserPointsPo;

import java.util.Date;
import java.util.Objects;

@DubboService
public class PointsService implements IPointsService {

    @Autowired
    private IUserPointsDao userPointsDao;

    @Override
    public void incr(PointsIncrDto pointsIncrDto) {
        //查询用户是否有积分数据
        LambdaQueryWrapper<UserPointsPo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPointsPo::getUserId, pointsIncrDto.getUserId());
        UserPointsPo userPointsPo = userPointsDao.selectOne(queryWrapper);
        //没有添加积分记录
        if(Objects.isNull(userPointsPo)) {
            userPointsPo = new UserPointsPo();
            userPointsPo.setUserId(pointsIncrDto.getUserId());
            userPointsPo.setPoints(pointsIncrDto.getPoints());
            userPointsPo.setCreateTime(new Date());
            userPointsPo.setUpdateTime(userPointsPo.getCreateTime());
            userPointsDao.insert(userPointsPo);
        }
        //有增加积分
        else {
            int result = userPointsDao.incr(userPointsPo.getId(), pointsIncrDto.getPoints(), new Date());
            if(!SqlHelper.retBool(result)) {
                //throw new ProviderException("修改用户积分异常");
                throw new BusinessException("修改用户积分异常");
            }
        }
    }
}
